"""
任务模型
"""

from datetime import datetime
from enum import Enum
from app import db


class TaskStatus(Enum):
    """任务状态枚举"""
    TODO = "todo"
    IN_PROGRESS = "in_progress"
    REVIEW = "review"
    DONE = "done"
    CANCELLED = "cancelled"


class TaskPriority(Enum):
    """任务优先级枚举"""
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    URGENT = "urgent"


class Task(db.Model):
    """任务模型"""
    __tablename__ = 'tasks'
    
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False)
    description = db.Column(db.Text, nullable=True)
    status = db.Column(db.Enum(TaskStatus), default=TaskStatus.TODO, nullable=False)
    priority = db.Column(db.Enum(TaskPriority), default=TaskPriority.MEDIUM, nullable=False)
    
    # 外键
    creator_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    assignee_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
    project_id = db.Column(db.Integer, db.ForeignKey('projects.id'), nullable=True)
    
    # 时间字段
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    due_date = db.Column(db.DateTime, nullable=True)
    completed_at = db.Column(db.DateTime, nullable=True)
    
    # 其他字段
    estimated_hours = db.Column(db.Float, nullable=True)
    actual_hours = db.Column(db.Float, nullable=True)
    tags = db.Column(db.String(500), nullable=True)  # 逗号分隔的标签
    
    # 关系
    comments = db.relationship('TaskComment', backref='task', lazy='dynamic', cascade='all, delete-orphan')
    attachments = db.relationship('TaskAttachment', backref='task', lazy='dynamic', cascade='all, delete-orphan')
    
    def __repr__(self):
        return f'<Task {self.title}>'
    
    def to_dict(self):
        """转换为字典"""
        try:
            return {
                'id': self.id,
                'title': self.title,
                'description': self.description,
                'status': self.status.value,
                'priority': self.priority.value,
                'creator_id': self.creator_id,
                'assignee_id': self.assignee_id,
                'project_id': self.project_id,
                'created_at': self.created_at.isoformat() if self.created_at else None,
                'updated_at': self.updated_at.isoformat() if self.updated_at else None,
                'due_date': self.due_date.isoformat() if self.due_date else None,
                'completed_at': self.completed_at.isoformat() if self.completed_at else None,
                'estimated_hours': self.estimated_hours,
                'actual_hours': self.actual_hours,
                'tags': self.tags.split(',') if self.tags else [],
                'creator': self.creator.to_dict() if hasattr(self, 'creator') and self.creator else None,
                'assignee': self.assignee.to_dict() if hasattr(self, 'assignee') and self.assignee else None,
                'project': self.project.to_dict() if hasattr(self, 'project') and self.project else None
            }
        except Exception as e:
            # 如果关系对象访问失败，返回基本信息
            return {
                'id': self.id,
                'title': self.title,
                'description': self.description,
                'status': self.status.value,
                'priority': self.priority.value,
                'creator_id': self.creator_id,
                'assignee_id': self.assignee_id,
                'project_id': self.project_id,
                'created_at': self.created_at.isoformat() if self.created_at else None,
                'updated_at': self.updated_at.isoformat() if self.updated_at else None,
                'due_date': self.due_date.isoformat() if self.due_date else None,
                'completed_at': self.completed_at.isoformat() if self.completed_at else None,
                'estimated_hours': self.estimated_hours,
                'actual_hours': self.actual_hours,
                'tags': self.tags.split(',') if self.tags else []
            }
    
    def update_status(self, new_status):
        """更新任务状态"""
        self.status = new_status
        self.updated_at = datetime.utcnow()
        
        if new_status == TaskStatus.DONE:
            self.completed_at = datetime.utcnow()
        elif new_status != TaskStatus.DONE and self.completed_at:
            self.completed_at = None
        
        db.session.commit()
    
    def is_overdue(self):
        """检查任务是否过期"""
        if not self.due_date or self.status == TaskStatus.DONE:
            return False
        return datetime.utcnow() > self.due_date
    
    def get_progress_percentage(self):
        """获取任务进度百分比"""
        if self.status == TaskStatus.DONE:
            return 100
        elif self.status == TaskStatus.IN_PROGRESS:
            return 50
        elif self.status == TaskStatus.REVIEW:
            return 75
        else:
            return 0
    
    def add_comment(self, user_id, content):
        """添加评论"""
        from .task_comment import TaskComment
        comment = TaskComment(
            task_id=self.id,
            user_id=user_id,
            content=content
        )
        db.session.add(comment)
        db.session.commit()
        return comment
    
    def get_tags_list(self):
        """获取标签列表"""
        return self.tags.split(',') if self.tags else []
    
    def set_tags(self, tags_list):
        """设置标签"""
        self.tags = ','.join(tags_list) if tags_list else None
    
    @classmethod
    def get_by_status(cls, status):
        """根据状态获取任务"""
        return cls.query.filter_by(status=status).all()
    
    @classmethod
    def get_by_assignee(cls, user_id):
        """获取分配给指定用户的任务"""
        return cls.query.filter_by(assignee_id=user_id).all()
    
    @classmethod
    def get_overdue_tasks(cls):
        """获取过期任务"""
        return cls.query.filter(
            cls.due_date < datetime.utcnow(),
            cls.status != TaskStatus.DONE
        ).all()
